#!/usr/bin/python3
# _*_coding:utf8_*_

'''
 * Created with IntelliJ Pycharm.
 * Description:  
 * Project : ops-toosl
 * Ide tools : PyCharm
 * File name : BasicDeploymentScripts.py
 * Author <a href="mailto:3245554@qq.com">罗卫</a>
 * User: devops
 * Date: 2019/9/4
 * Time: 上午10:00
'''

'''
根据主机名判断基础部署内容：
'''

import socket,re,subprocess,os,urllib.request,psutil,threading,sys,shutil
from netaddr import *

thread_res_list = []

class Thread(threading.Thread):

    def __init__(self,func,name,arg):
        threading.Thread.__init__(self)
        self.func = func
        self.name = name
        self.arg = arg
        self.res = thread_res_list

    def run(self):
        result = self.func(self.arg)
        self.res.append(result)

def moveFileto(sourceDir,  targetDir):
    shutil.copy(sourceDir,  targetDir)

def up_net_car():
    isupnetcar = psutil.net_if_stats()
    isupnetcar.pop('lo')
    for i in isupnetcar:
        if isupnetcar[i].isup:
            print('net car: %s'%i)
            return i

def get_ipv4_net_mask(net_car_name,confirm_ip):
    addr = psutil.net_if_addrs()
    net_car = addr[net_car_name]
    for i in net_car:
        if i.family == 2:
            if i.address == confirm_ip:
                print('netmask: %s'%i.netmask)
                return i.netmask

def getsubnet(netmask):
    result = ""
    if netmask != None:
        for num in netmask.split('.'):
            temp = str(bin(int(num)))[2:]
            result = result + temp
            subnet = len("".join(str(result).split('0')[0:1]))
        # print('subnet: %s'%subnet)
        return subnet
    else:
        print('netmask is None。')
        sys.exit(0)

def byip_maskgetCIDR(ip,subnet):
    ips = ip.split('.')
    if ip != None and subnet != None:
        if subnet <= 24:
            ips[3] = 0
            cidr = ipstr(ips, subnet)
            print('网段: %s'%cidr)
            return cidr

        elif subnet <= 16:
            ips[2] = 0
            ips[3] = 0
            cidr = ipstr(ips, subnet)
            print('CIDR: %s'%cidr)
            return cidr
        elif subnet <= 8:
            ips[2] = 0
            ips[3] = 0
            ips[1] = 0
            cidr = ipstr(ips, subnet)
            print('CIDR: %s' % cidr)
            return cidr
    else:
        print('ip or subnet is None')
        sys.exit(0)

def ipstr(ips,subnet):
    res_ip = ''
    for i in ips:
        res_ip += '%s.' % i
    CIDR = '%s/%d' % (res_ip[:-1], subnet)
    return CIDR

def byCIDRiplist(CIDR):
    ip_list = []
    if CIDR !=None:
        ip = IPNetwork(CIDR)
        cidr_ip_list = list(ip)
        # print('subnet : %s '%CIDR)
        for i in cidr_ip_list:
            b = i.bin[-8::].encode('utf-8')
            if b != b'00000000' and b != b'11111111':
                ip_list.append(str(i))
                # print('\t%s'%str(i))
        return ip_list
    else:
        print('CIDR is None')
        sys.exit(0)

def ping_onlin_host(ip_list):
    '''
    内网不能禁ping，否则无在线主机。
    :param ip_list:
    :return:
    '''
    if ip_list != None:
        thread_list = []
        print('在线主机列表\n')
        for i in ip_list:
            cmd = 'ping -c 1 %s'%i
            thread = Thread(command,'thread-%s'%i,cmd)
            thread_list.append(thread)
        for t in thread_list:
            t.start()
        if len(thread_res_list) == len(thread_list):
            onlin_host = onlin_list()
            return onlin_host
        else:
            print('线程未执行完成，等待5秒……')
            import time
            time.sleep(5)
            onlin_host = onlin_list()
            return onlin_host
    else:
        print('ip list is None')
        sys.exit(0)

def onlin_list():
    onlin_host = []
    for p in thread_res_list:
        if p[0] != 1:
            tmp = p[1].split(' ')
            onlin_ip = tmp[1]
            onlin_host.append(onlin_ip)
            print('\t%s' % onlin_ip)
    return onlin_host

def gethostname():
    return socket.gethostname()

def getlanaddr():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        print('local ip : %s'%ip)
        return ip
    except Exception as e:
        print(e)

def getlanremoteaddr(hostname):
    localip = getlanaddr()
    net_cat = up_net_car()
    localmask = get_ipv4_net_mask(net_cat,localip)
    subnet = getsubnet(localmask)
    CIDR = byip_maskgetCIDR(localip,subnet)
    subnet_ip_list = byCIDRiplist(CIDR)
    onlin_host = ping_onlin_host(subnet_ip_list)
    for i in onlin_host:
        try:
            host_name = socket.gethostbyaddr(i)
            print('ip:%s -> hostname:%s'%(i,str(host_name)))
            if host_name[0] == hostname:
                return i
            else:
                print('not find "%s" host'%hostname)
                sys.exit(0)
        except Exception as e:
            print(e)

def command(arg):
    try:
        res = subprocess.getstatusoutput(arg)
        return res
    except Exception as e:
        print(e)

def writefile(path,data):
    try:
        with open(path,'w+') as f:
            f.write(data)
    except Exception as e:
        print(e)

def modify_nginx_base_conf():
    base_conf = '''# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 65535;
    multi_accept on;
    use epoll;
}

http {
    log_format  main  "$remote_addr -- $remote_user - [$time_local] - $request 
                      $status - $body_bytes_sent - $http_referer
                      $http_user_agent - $http_x_forwarded_for";

    access_log  /var/log/nginx/access.log  main;
    include     /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   0;
    types_hash_max_size 4096;
    server_tokens       off;
    client_header_buffer_size 64k;
    large_client_header_buffers 4 64k;
    client_header_timeout 60;
    client_body_timeout 120;
    reset_timedout_connection on;
    send_timeout 60;

    # gzip压缩功能设置  

    gzip  on;
    gzip_disable "msie6";
    gzip_proxied any;
    gzip_buffers 4 8k;
    gzip_min_length 1024;
    gzip_comp_level 9;
    gzip_vary on;
    gzip_types font/ttf font/otf image/svg+xml image/png image/x-icon image/jpeg image/gif text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    #http_proxy 设置

    client_max_body_size 300m;
    client_body_buffer_size 200m;
    proxy_connect_timeout 600;
    proxy_send_timeout 75;
    proxy_read_timeout 600;
    proxy_buffer_size 8096k;
    proxy_buffers 4 8096k;
    proxy_busy_buffers_size 8096k;
    proxy_temp_file_write_size 8096k;
    proxy_temp_path /var/lib/nginx/proxy 1 2;
    
}'''
    base_conf_path = "/etc/nginx/nginx.conf"
    res = writefile(base_conf_path,base_conf)
    print(res)
    restart_nginx()

def restart_nginx():
    restart_res = command('systemctl restart nginx')
    print(restart_res)

def local_load_default_conf(port):
    if port == 1002:
        listen = 8694
        name = 'gate'
        conf_path = '/etc/nginx/conf.d/gate.conf'
    elif port == 4002:
        listen = 8846
        name = 'login'
        conf_path = '/etc/nginx/conf.d/login.conf'
    elif port == 8081:
        listen = 80
        name = 'pay'
        conf_path = '/etc/nginx/conf.d/pay.conf'
    elif port == 8089:
        listen = 80
        name = 'git'
        conf_path = '/etc/nginx/conf.d/git.conf'
    else:
        listen = 80
        port = 8009
        name = 'promotion'
        conf_path = '/etc/nginx/conf.d/default.conf'
    default_conf = '''server {
    listen       %d;
    server_name  _;
    location / {
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass http://127.0.0.1:%d;
    }
        access_log /var/log/nginx/%s_access.log;
}

    '''%(listen,port,name)
    writefile(conf_path,default_conf)
    restart_nginx()

def mkdir_chcek(path):
    '''
    #完成路径
    :param path: :type:str
    :return:
    '''
    Separator = '/'
    tmp = ''
    print('%s is dir'%path)
    paths = path.split(Separator)
    if re.findall(r'[\*\.conf]$',paths[len(paths)-1]):
        print(paths[len(paths)-1])
        paths.remove(paths[len(paths)-1])
    paths.remove('')
    for i in paths:
        tmp += '%s%s'%(Separator,i)
        if os.path.exists(tmp)is False:
            os.mkdir(tmp,0o777)
            print('mkdir %s'%tmp)

def install_nginx():
    adduser_res = command('adduser nginx')
    print(adduser_res)
    nginx_source_path = "/etc/yum.repos.d/nginx.repo"
    nginx_source = "[nginx]\nname=nginx repo\nbaseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/\ngpgcheck=0\nenabled=1"
    writefile(nginx_source_path,nginx_source)
    mkdir_chcek("/var/lib/nginx/proxy")
    os.chown('/var/lib/nginx/proxy',1000,1000)
    nignx_in = command("yum install nginx -y")
    print(nignx_in)
    modify_nginx_base_conf()
    restart_nginx = command("systemctl start nginx")
    print(restart_nginx)

def install_jdk():
    jdk_in = command("yum install java-1.8.0-openjdk* -y")
    print(jdk_in)

def install_tomcat():
    res = command("yum install tomcat -y")
    print(res)
    with open('/etc/tomcat/server.xml','r')as f:
        data = f.read()
        new_data = data.replace('8080','8089')
        with open('/etc/tomcat/server.xml','w')as f:
            f.write(new_data)

def gitdeployment():
    if os.path.exists('/usr/share/tomcat/webapps'):
        req = urllib.request
        req.urlretrieve('http://dl.bintray.com/gitblit/releases/gitblit-1.8.0.war', '/usr/share/tomcat/webapps/ROOT.war')
        res = command('systemctl start tomcat')
        print(res)
    else:
        print('not tomcat webapps path ')

def install_mongodb():
    mongodb_source = '[mongodb-org-4.0]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.0/x86_64/' \
                     '\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc'
    mongodb_source_path = '/etc/yum.repos.d/mongodb-org-4.0.repo'
    writefile(mongodb_source_path,mongodb_source)
    command('yum install mongodb-org* -y')
    if os.path.isfile('/etc/mongod.conf'):
        os.remove('/etc/mongod.conf')

def make_auth_key():
    key_path = '/home/DB-DATA/auth_key'
    res = command('openssl rand -base64 512')
    if res[0] == 0:
        key = res[1]
        writefile(key_path,key)
    else:
        print('生成key异常：')
        print(res[1])

def configuration_config_colony_config(port):
    for i in port:
        index_ = port.index(i)
        db_path = '/home/DB-DATA/mongo_config-%d'%index_
        mkdir_chcek(db_path)
        conf = '''# mongoconfig.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod_config-%d.log

# Where and how to store data.
storage:
  dbPath: %s
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
     engineConfig:
        cacheSizeGB: 6
        journalCompressor: snappy
        directoryForIndexes: false
     collectionConfig:
        blockCompressor: snappy
     indexConfig:
        prefixCompression: true
sharding:
    clusterRole: configsvr
replication:
    replSetName: configs

#  engine:
#  mmapv1:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongo_config-%d.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: %d
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
security:
  keyFile: /home/DB-DATA/auth_key
  authorization: enabled'''%(index_,db_path,index_,i)
        db_conf_path = '/etc/mongodb/mongo_config-%d.conf'%index_
        start_mongod(db_conf_path,conf)

def start_mongod(conf_path,conf):
    mkdir_chcek(conf_path)
    print("mkdir: %s"%conf_path)
    writefile(conf_path, conf)
    res = command('mongod -f %s' % conf_path)
    print(res)

def start_mongos(conf_path,conf):
    mkdir_chcek(conf_path)
    print("mkdir: %s"%conf_path)
    writefile(conf_path, conf)
    res = command('mongos -f %s' % conf_path)
    print(res)

def configuration_db_colony_config(port):
    for i in port:
        index_ = port.index(i)
        db_path = '/home/DB-DATA/mongodb-%d/'%index_
        mkdir_chcek(db_path)
        config = '''# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongodb-%d.log

# Where and how to store data.
storage:
  dbPath: %s
  journal:
    enabled: true
  engine: wiredTiger
  wiredTiger:
     engineConfig:
        cacheSizeGB: 6
        journalCompressor: snappy
        directoryForIndexes: false
     collectionConfig:
        blockCompressor: snappy
     indexConfig:
        prefixCompression: true
sharding:
    clusterRole: shardsvr
replication:
    replSetName: rs1

#  engine:
#  mmapv1:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongod_db-%d.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: %d
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
security:
  keyFile: /home/DB-DATA/auth_key
  authorization: enabled'''%(index_,db_path,index_,i)
        db_conf_path = '/etc/mongodb/mongodb-%d.conf'%index_
        start_mongod(db_conf_path,config)

def configuration_mongos():
    config_host = getlanaddr()
    if config_host != None:
        conf_path = '/etc/mongodb/mongos.conf'
        conf = '''systemLog:
    quiet: false
    path: /var/log/mongodb/mongos.log
    logAppend: false
    destination: file
sharding:
    configDB: configs/%s:37017,%s:37018,%s:37019
processManagement:
    fork: true
    pidFilePath: /var/run/mongodb/mongos.pid
net:
    bindIp: 0.0.0.0
    port: 31000
    maxIncomingConnections: 65535
    wireObjectCheck: true
    ipv6: false
security:
  keyFile: /home/DB-DATA/auth_key'''%(config_host,config_host,config_host)
        start_mongos(conf_path,conf)
    else:
        print('[ERROR]：mongos conf not write,not get local ip address。')

def configuration_main_mongodb():
    db_port = [27017]
    conf_port = [37017,37018,37019]
    configuration_db_colony_config(db_port)
    configuration_config_colony_config(conf_port)

def configuration_backup_mongodb():
    db_port = [27018,27019]
    configuration_db_colony_config(db_port)

def rewrite_redis_conf():
    redis_conf_path = '/etc/redis.conf'
    with open(redis_conf_path,'r')as f:
        data = f.read()
        data_list = data.split("\n")
        os.rename(redis_conf_path, '%s.bak'%redis_conf_path)
        with open('/etc/redis.conf', 'w')as r:
            for i in data_list:
                if not re.match('^#', i) :
                    if i == 'bind 127.0.0.1':
                        r.write('bind 0.0.0.0\n')
                elif i == '# requirepass foobared':
                    r.write('requirepass 9aPcd5\n')
                else:
                    r.write('%s\n' % i)

def install_redis():
    try:
        epel_res = command('yum install epel-release -y')
        print(epel_res)
        remi_rpm_res = command('rpm -ivh http://rpms.remirepo.net/enterprise/7/remi/x86_64/remi-release-7.6-2.el7.remi.noarch.rpm')
        print(remi_rpm_res)
        redis_res = command('yum --enablerepo=remi install redis -y')
        print(redis_res)
    except Exception as e:
        redis_res = command('rpm -ivh http://rpms.remirepo.net/enterprise/7/remi/x86_64/redis-5.0.5-1.el7.remi.x86_64.rpm')
        print(redis_res)
    rewrite_redis_conf()
    res = command('systemctl start redis')
    print(res)

def _install_mysqld():
    '''弃用'''
    pass

def mongodb_db(ip1,ip2):
    wirtepath = 'rs_db_initiate.js'
    data = "rs.initiate({_id: 'rs1', members: [{_id: 0, host: '%s:27017'}, {_id: 1, host: '%s:27018'},{_id: 2, host: '%s:27019'}]})"%(ip1,ip2,ip2)
    writefile(wirtepath,data)
    res = command('mongo --port 27017 %s'%wirtepath)
    print(res)

def mongodb_config(ip):
    wirtepath = 'rs_conf_initiate.js'
    data = "rs.initiate({_id : 'configs',configsvr: true,members : [{_id : 0, host : '%s:37017' },{_id : 1, host : '%s:37018' },{_id : 2, host : '%s:37019'}]})"%(ip,ip,ip)
    writefile(wirtepath,data)
    res = command('mongo --port 37017 %s'%wirtepath)
    print(res)

def mongos_conf(ip1,ip2):
    wirtepath = 'mongos_addshard.js'
    data = 'use admin\ndb.runCommand({addshard:"rs1/%s:27017,%s:27018,%s:27019"});'%(ip1,ip2,ip2)
    writefile(wirtepath,data)
    res = command('mongo --port 31000 %s'%wirtepath)#mongo报语法错误
    print(res)

#db.createUser({user:"root",pwd:"WER123zxc-!asd",roles:[{role:"readWrite",db:"unknown_game_server"},{role:"readWrite",db:"unknown_game_server"}]});

def closefirwalld():
    res = command('systemctl stop firewalld')
    print(res)

def install_zookpeer():
    download_url = 'http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.5.5/apache-zookeeper-3.5.5-bin.tar.gz'
    try:
        urllib.request.urlretrieve(download_url, 'zookeeper.tar.gz')
    except Exception as e:
        print(e)
    res = command('tar -zxvf zookeeper.tar.gz -C /opt/')
    if res[0] == 0:
        zookeeper_start = '#/bin/bash\n\ncd /opt/apache-zookeeper-3.5.5-bin/bin\nchmod 775 zkServer.sh\n./zkServer.sh start'
        moveFileto('/opt/apache-zookeeper-3.5.5-bin/conf/zoo_sample.cfg', '/opt/apache-zookeeper-3.5.5-bin/conf/zoo.cfg')
        writefile('tmp.sh', zookeeper_start)
        zookeeper_res = command('sh tmp.sh')
        if zookeeper_res[0] == 0:
            print('zookeeper STARTED')
        else:
            print('zookeeper FAILED')
    else:
        print('解压zookeeper安装包出错，请看下面错误信息。')
        print(res)



def web():
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_nginx()
    print('-------------------------nginx安装完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')

def db(mongodb_m_ip,mongodb_b_ip):
    closefirwalld()
    print('-------------------------关闭系统防火墙-------------------------------------------------')
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_redis()
    print('-------------------------redis安装完成，并已启动，如未启动，请检查-------------------------------------------------')
    make_auth_key()
    print('----------------------------生成mongo集群认证key-----------------------------------------')
    install_mongodb()
    print('-------------------------mongodb安装完成-------------------------------------------------')
    configuration_main_mongodb()
    print('------------------------- db服 mongodb配置完成-------------------------------------------------')
    mongodb_db(mongodb_m_ip,mongodb_b_ip)
    print('------------------------- db服 mongodb集群初始化完成-------------------------------------------------')
    mongodb_config(mongodb_m_ip)
    print('------------------------- db服 mongodb 配置集群配置完成-------------------------------------------------')
    configuration_mongos()
    print('------------------------- db服 mongos配置完成-------------------------------------------------')
    mongos_conf(mongodb_m_ip,mongodb_b_ip)
    print('------------------------- db服 mongos配置初始化完成-------------------------------------------------')

def backup():
    closefirwalld()
    print('-------------------------关闭系统防火墙-------------------------------------------------')
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_tomcat()
    print('-------------------------tomcat安装完成-------------------------------------------------')
    install_nginx()
    print('-------------------------nginx安装完成-------------------------------------------------')
    local_load_default_conf(8089)
    print('-------------------------nginx git配置初始化完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')
    gitdeployment()
    print('-------------------------tomcat git应用包发布完成-------------------------------------------------')
    make_auth_key()
    print('----------------------------生成mongo集群认证key-----------------------------------------')
    install_mongodb()
    print('-------------------------mongodb安装完成-------------------------------------------------')
    configuration_backup_mongodb()
    print('------------------------- db服 mongodb 配置集群配置完成-------------------------------------------------')
    install_zookpeer()
    print('------------------------- zookeeper安装完成，并已启动-------------------------------------------------')

def gate():
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_nginx()
    print('-------------------------nginx安装完成-------------------------------------------------')
    local_load_default_conf(1002)
    print('-------------------------nginx网关配置初始化完成-------------------------------------------------')
    local_load_default_conf(4002)
    print('-------------------------nginx登录配置初始化完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')

def login():
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_nginx()
    print('-------------------------nginx安装完成-------------------------------------------------')
    local_load_default_conf(4002)
    print('-------------------------nginx登录配置初始化完成-------------------------------------------------')
    local_load_default_conf(1002)
    print('-------------------------nginx网关配置初始化完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')

def game():
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')

def pay():
    base()
    print('-------------------------基本初始化优化完成-------------------------------------------------')
    install_nginx()
    print('-------------------------nginx安装完成-------------------------------------------------')
    local_load_default_conf(8081)
    print('-------------------------nginx默认配置初始化完成-------------------------------------------------')
    install_jdk()
    print('-------------------------jdk安装完成-------------------------------------------------')

def base():
    res = command('cat /etc/sysctl.conf|grep net.ipv4.tcp_tw_recycle')
    if res[0] != 0:
        base = '''﻿#!/bin/bash

platform=`uname -i`
if [ $platform != "x86_64" ];then
echo "this script is only for 64bit Operating System !"
exit 1
fi
echo "the platform is ok"
cat << EOF
+---------------------------------------+
|   your system is CentOS 7 x86_64      |
|      start optimizing.......          |
+---------------------------------------
EOF



yum clean all
yum makecache

# update os or soft
yum update -y
echo y

# man chinese pages
yum install man-pages-zh-CN.noarch  -y
# Conventional tools
yum install ntp wget git tcpdump net-tools -y
yum install vim lrzsz zip unzip epel-release -y
#install jdk-1.8.0-openjdk

timedatectl set-timezone Asia/Shanghai
/usr/sbin/ntpdate cn.pool.ntp.org
echo "* 4 * * * /usr/sbin/ntpdate cn.pool.ntp.org > /dev/null 2>&1" >> /var/spool/cron/root
systemctl  restart crond.service

#yum install java-1.8.0-openjdk* -y
#wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

echo "ulimit -SHn 102400" >> /etc/rc.local
cat >> /etc/security/limits.conf << EOF
*           soft   nofile       655350
*           hard   nofile       655350
EOF


sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
setenforce 0


# Ban ping
#echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_all

# vim optimization
echo 'alias vi=vim' >> /etc/profile
#echo 'stty erase ^H' >> /etc/profile
cat >> /root/.vimrc << EOF
set tabstop=4
set shiftwidth=4
set expandtab
set helplang=cn
set encoding=utf-8
set fileencodings=ucs-bomo,utf-8,chinese,gbk,latin-1
set ffs=unix,dos,mac
set backspace=indent,eol,start
set whichwrap=b,s,<,>,[,]
set number
EOF

# kernel optimization
cat >> /etc/sysctl.conf << EOF
#CTCDN系统优化参数
#关闭ipv6
#net.ipv6.conf.all.disable_ipv6 = 1
#net.ipv6.conf.default.disable_ipv6 = 1
#决定检查过期多久邻居条目
net.ipv4.neigh.default.gc_stale_time=120
#使用arp_announce / arp_ignore解决ARP映射问题
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.all.arp_announce=2
net.ipv4.conf.lo.arp_announce=2
# 避免放大攻击
net.ipv4.icmp_echo_ignore_broadcasts = 1
# 开启恶意icmp错误消息保护
net.ipv4.icmp_ignore_bogus_error_responses = 1
#开启路由转发
net.ipv4.ip_forward = 1
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
#开启反向路径过滤
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
#处理无源路由的包
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
#关闭sysrq功能
kernel.sysrq = 0
#core文件名中添加pid作为扩展名
kernel.core_uses_pid = 1
# 开启SYN洪水攻击保护
net.ipv4.tcp_syncookies = 1
#修改消息队列长度
kernel.msgmnb = 65536
kernel.msgmax = 65536
#设置最大内存共享段大小bytes
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
#timewait的数量，默认180000
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096        87380   4194304
net.ipv4.tcp_wmem = 4096        16384   4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
#每个网络接口接收数据包的速率比内核处理这些包的速率快时，允许送到队列的数据包的最大数目
#net.core.netdev_max_backlog = 262144
#限制仅仅是为了防止简单的DoS 攻击
net.ipv4.tcp_max_orphans = 3276800
#未收到客户端确认信息的连接请求的最大值
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
#内核放弃建立连接之前发送SYNACK 包的数量
net.ipv4.tcp_synack_retries = 1
#内核放弃建立连接之前发送SYN 包的数量
net.ipv4.tcp_syn_retries = 1
#启用timewait 快速回收
net.ipv4.tcp_tw_recycle = 1
#开启重用。允许将TIME-WAIT sockets 重新用于新的TCP 连接
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
#当keepalive 起用的时候，TCP 发送keepalive 消息的频度。缺省是2 小时
net.ipv4.tcp_keepalive_time = 1800
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 15
#允许系统打开的端口范围
#net.ipv4.ip_local_port_range = 1024    65000
#修改防火墙表大小，默认65536
#net.netfilter.nf_conntrack_max=655350
#net.netfilter.nf_conntrack_tcp_timeout_established=1200
# 确保无人能修改路由表
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
#优化redis启动警告
vm.overcommit_memory = 1
net.core.somaxconn=32768
EOF
echo never > /sys/kernel/mm/transparent_hugepage/enabled
sysctl -p


# After landing display information
echo "It is product environment,be careful..." > /etc/motd

# Ban Ctrl+Alt+Del
mv /usr/lib/systemd/system/ctrl-alt-del.target /usr/lib/systemd/system/ctrl-alt-del.target.bakup
init q

# Add user
# echo "Please enter your user name"
# read user
# useradd $user
# for (( i=0; i <= 3; i++ ))
# do
    # echo "Please enter the password"
    # read password
    # echo "try aging enter the password"
    # read passwordtry
    # if [ $password == $passwordtry ]; then
        # passwd $user $password
    # else
        # echo "Two input password, please try again!"
    # fi
# done
# Lock key file system
#chattr +i /etc/passwd
#chattr +i /etc/inittab
#chattr +i /etc/group
#chattr +i /etc/shadow
#chattr +i /etc/gshadow

#mv /usr/bin/chattr /usr/bin/chattrs

# Remove unwanted users
userdel adm
userdel lp
userdel sync
userdel shutdown
userdel halt
userdel news
userdel uucp
userdel operator
userdel games
userdel gopher
userdel ftp
# Remove unnecessary group
groupdel adm
groupdel lp
groupdel news
groupdel uucp
groupdel games
groupdel dip
groupdel pppusers

#create project deploye files

roots="new_project"
down="download"
git="git"
#shell="shells"

mkdir /home/$roots
mkdir /home/$roots/$down
mkdir /home/$roots/$down/$git
#mkdir /home/$roots/$down/$shells'''
        writefile('base.sh',base)
        base_res = command('sh base.sh')
        print(base_res)

if __name__ == '__main__':

    #获取主机名
    HOST = gethostname()
    #下面填写服务内网ip。
    # 如果pay与web合并部署，pay空着不填
    # 如果游戏网关和登录与游戏合并部署网关和登录不填
    #game 目前可填可不填，后期啊做服务配置做预留
    #web 目前可默认不填
    host_ip = {
        "db":"172.16.100.133",
        "backup":"172.16.100.130",
        "gate":"",
        "login":"",
        "game":"",
        "web":"",
        "pay":""
    }
    if host_ip["gate"] == "" and host_ip["login"] == "":
        if host_ip["pay"] == "":
            if HOST == 'WEB' or HOST == 'web' or re.search('WEB', HOST) or re.search('web', HOST):
                web()
                local_load_default_conf(80)
            elif HOST == 'DB' or HOST == 'db' or re.search('DB', HOST) or re.search('db', HOST):
                db(host_ip["db"],host_ip["backup"])
            elif HOST == 'BACKUP' or HOST == 'backup' or re.search('BACKUP', HOST) or re.search('backup', HOST):
                backup()
            elif HOST == 'GAME' or HOST == 'game' or re.search('GAME', HOST) or re.search('game', HOST):
                gate()
        else:
            if HOST == 'WEB' or HOST == 'web' or re.search('WEB', HOST) or re.search('web', HOST):
                web()
            elif HOST == 'DB' or HOST == 'db' or re.search('DB', HOST) or re.search('db', HOST):
                db(host_ip["db"],host_ip["backup"])
            elif HOST == 'BACKUP' or HOST == 'backup' or re.search('BACKUP', HOST) or re.search('backup', HOST):
                backup()
            elif HOST == 'GAME' or HOST == 'game' or re.search('GAME', HOST) or re.search('game', HOST):
                gate()
            elif HOST == 'PAY' or HOST == 'pay' or re.search('PAY', HOST) or re.search('pay', HOST):
                pay()
    else:
        #判断主机
        if host_ip["pay"] == "":
            if HOST == 'WEB' or HOST == 'web' or re.search('WEB',HOST) or re.search('web',HOST):
                web()
            elif HOST == 'DB' or HOST == 'db' or re.search('DB',HOST) or re.search('db',HOST):
                db(host_ip["db"],host_ip["backup"])
            elif HOST == 'BACKUP' or HOST == 'backup' or re.search('BACKUP',HOST) or re.search('backup',HOST):
                backup()
            elif HOST == 'GATE' or HOST == 'gate' or re.search('GATE',HOST) or re.search('gate',HOST):
                gate()
            elif HOST == 'LOGIN' or HOST == 'login' or re.search('LOGIN',HOST) or re.search('login',HOST):
                login()
            elif HOST == 'GAME' or HOST == 'game' or re.search('GAME',HOST) or re.search('game',HOST):
                game()
        else:
            if HOST == 'WEB' or HOST == 'web' or re.search('WEB',HOST) or re.search('web',HOST):
                web()
            elif HOST == 'DB' or HOST == 'db' or re.search('DB',HOST) or re.search('db',HOST):
                db(host_ip["db"],host_ip["backup"])
            elif HOST == 'BACKUP' or HOST == 'backup' or re.search('BACKUP',HOST) or re.search('backup',HOST):
                backup()
            elif HOST == 'GATE' or HOST == 'gate' or re.search('GATE',HOST) or re.search('gate',HOST):
                gate()
            elif HOST == 'LOGIN' or HOST == 'login' or re.search('LOGIN',HOST) or re.search('login',HOST):
                login()
            elif HOST == 'GAME' or HOST == 'game' or re.search('GAME',HOST) or re.search('game',HOST):
                game()
            elif HOST == 'PAY' or HOST == 'pay' or re.search('PAY',HOST) or re.search('pay',HOST):
                pay()